﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

using System.Collections;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

using Helper;
using Highlearner_API;

using Logging;


namespace Highlearner
{
	enum EState
	{
		Disconnected,
		Connected,
		Downloading,
	}

	public partial class FormMain : Form
	{
		private delegate void SetStatusDelegate(EState a_eState);

		private Boolean DEBUG_COURSE = false;

		private const string COURSES_FILE_PATH_END = "SavedCourses.dat";

		private String m_sCoursesFilePath = "";
		private bool m_bCoursesLoaded = false;
	
		private Miner_Highlearn.frm_Log FormLog;
		private Executer m_oCore;
		private Course m_oCurrentCourse = null;
		private FolderItem m_oCurrentFolder = null;

		private CListViewAnimator m_oAnimator;

		private int m_iDownloadFilesCount = 0;

		// States wether the tree view is populating. Good for knowing when to ignore certain events (like AfterCheck)
		private bool m_bTreeViewPopulating = false;

		private static string m_sConfigurationDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Highlearner\\";
		private string m_sConfigurationFilename = m_sConfigurationDirectory + "UserSettings.dat";


		public FormMain()
		{
			// Reset the downloads directory
			if (Properties.Settings.Default.SavePath == "")
			{
				Properties.Settings.Default.SavePath =
					Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\HighlearnerDownloads";
			}

			InitializeComponent();

			FormLog = new Miner_Highlearn.frm_Log();
			FormLog.Show();
			//edt_Log = FormLog.edt_Log;

			m_oAnimator = new CListViewAnimator(listViewCourses);

			CLogger.StartLogging(m_sConfigurationDirectory + "Log.csv");
		}

		public void Initialize()
		{
			m_oCore = new Executer();

			listViewCourses.Items.Clear();
			m_bCoursesLoaded = false;

			SetGUIState(EState.Disconnected);

			// Set the corresponding core for the current university
			switch (((EInstitute)Properties.Settings.Default.Institute))
			{
				case EInstitute.TAU:
					m_oCore.Core = (Miner_Highlearn.API_Highlearn)new Miner_Highlearn.API_HL_TAU();
					break;
				case EInstitute.HUJI:
					m_oCore.Core = (Miner_Highlearn.API_Highlearn)new Miner_Highlearn.API_HL_HUJI();
					break;
/*				case TMy_University.BIU:
					hl.core = (API_Highlearn)new API_HL_BIU();
					break;
				case TMy_University.BGU:
					hl.core = (API_Highlearn)new API_HL_BGU();
					break;
				case TMy_University.Haifa:
					hl.core = (API_Highlearn)new API_HL_Haifa();
					break;
				case TMy_University.Colman:
					hl.core = (API_Highlearn)new API_HL_Colman();
					break;
				case TMy_University.HIT:
					hl.core = (API_Highlearn)new API_HL_HIT();
					break;
				case TMy_University.Sapir:
					hl.core = (API_Highlearn)new API_HL_Sapir();
					break;
				case TMy_University.CET:
					hl.core = (API_Highlearn)new API_HL_CET();
					break;
				case TMy_University.Afeka:
					hl.core = (API_Highlearn)new API_HL_Afeka();
					break;
				case TMy_University.SCE:
					hl.core = (API_Highlearn)new API_HL_SCE();
					break;*/
			}
			m_oCore.SavePath = Properties.Settings.Default.SavePath;

			m_oCore.OnConnected += new SimpleDelegate(ExecuterConnected);
			m_oCore.OnDisconnected += new SimpleDelegate(ExecuterDisconnected);
			m_oCore.OnAuthenticationFailed += new SimpleDelegate(ExecuterAuthenticationFailed);
			m_oCore.OnCoursesLoadedEvent += new SimpleDelegate(ExecuterCoursesLoaded); 
			m_oCore.OnCourseInformationUpdated +=new CourseUpdatedDelegate(CourseInformationUpdated);
			m_oCore.OnCourseInformationRequest += new CourseUpdatedDelegate(CourseInformationRequest);
			m_oCore.OnFileDownloadStarted += new FileDownloadDelegate(FileDownloadStarted);
			m_oCore.OnFileDownloadEndedSuccessfully += new FileDownloadDelegate(FileDownloadEndedSuccessfully);
			m_oCore.OnFileDownloadFailed += new FileDownloadDelegate(FileDownloadFailed);
			m_oCore.OnCourseDownloadStarted += new DownloadStarted(CourseDownloadStarted);
			m_oCore.OnCourseDownloadEnded += new DownloadEnded(CourseDownloadEnded);
			m_oCore.OnDownloadStarted += new DownloadStarted(DownloadStarted);
			m_oCore.OnDownloadEnded += new DownloadEnded(DownloadEnded);

			m_oCore.Core.logger = new Logger();
			m_oCore.Core.logger.edt_Log = FormLog.edt_Log;
			m_oCore.Core.logger.frm_Parent = this;
			m_oCore.Core.logger.file_path = m_sConfigurationDirectory + "Log.txt";

			//			hl.prg_Courses				= prg_Courses;
			//			hl.edt_Progress_Course		= edt_Progress_Course;

			//			hl.core.prg_File			= prg_File;
			//			hl.core.edt_Progress_File	= edt_Progress_File;

			//edt_Log_Initial_Height = edt_Log.Height;
			//edt_Verbose_Level_ValueChanged(null, null);

			if (File.Exists(m_oCore.Core.logger.file_path))
			{
				File.Delete(m_oCore.Core.logger.file_path);
			}
		}

		private void UpdateCurrentStatus(String a_sMessage)
		{
			toolStripStatusLabelCurrentStatus.Text = a_sMessage;
		}

		private void UpdateGeneralStatus(String a_sMessage)
		{
			toolStripStatusLabelGeneralStatus.Text = a_sMessage;
		}

		#region Executer Events

		void ExecuterConnected()
		{
			this.Invoke(new SetStatusDelegate(SetGUIState), EState.Connected);
		}
		void ExecuterDisconnected()
		{
			this.Invoke(new SetStatusDelegate(SetGUIState), EState.Disconnected);
		}
		void ExecuterAuthenticationFailed()
		{
			// Thread Safe Updating
			this.Invoke(new SimpleDelegate(ExecuterAuthenticationFailedSafe));
		}
		void ExecuterAuthenticationFailedSafe()
		{

		}

		void CourseDownloadStarted(Course a_oCourse, int a_iNumberOfItems)
		{
			// Thread Safe Updating
			this.Invoke(new DownloadStarted(CourseDownloadStartedSafe), a_oCourse, a_iNumberOfItems);
		}
		void CourseDownloadStartedSafe(Course a_oCourse, int a_iNumberOfItems)
		{
			m_iDownloadFilesCount = a_iNumberOfItems;
			toolStripProgressBar.Maximum = a_iNumberOfItems;
		}
		void CourseDownloadEnded(Course a_oCourse)
		{
			// Thread Safe Updating
			this.Invoke(new DownloadEnded(CourseDownloadEndedSafe), a_oCourse);
		}
		void CourseDownloadEndedSafe(Course a_oCourse)
		{
		}
	
		void DownloadStarted(Course a_oCourse, int a_iNumberOfItems)
		{
			// Thread Safe Updating
			this.Invoke(new DownloadStarted(DownloadStartedSafe), a_oCourse, a_iNumberOfItems);
		}
		void DownloadStartedSafe(Course a_oCourse, int a_iNumberOfItems)
		{
			SetGUIState(EState.Downloading);
		}
		void DownloadEnded(Course a_oCourse)
		{
			// Thread Safe Updating
			this.Invoke(new DownloadEnded(DownloadEndedSafe), a_oCourse);
		}
		void DownloadEndedSafe(Course a_oCourse)
		{
			SetGUIState(EState.Connected);
			UpdateCurrentStatus("ההורדה הסתיימה");

			toolStripProgressBar.Value = toolStripProgressBar.Maximum;

			System.Diagnostics.Process.Start(m_oCore.Core.SavePath);
		}

		void FileDownloadFailed(Course a_oCourse, FolderItem a_oFolder, FileItem a_oFile)
		{
			m_oCore.Core.logger.WriteLn("File " + a_oFolder.Name + "\\" + a_oFile.Name + " failed downloading");

			// Thread Safe Updating
			this.Invoke(new FileDownloadDelegate(FileDownloadFailedSafe), a_oCourse, a_oFolder, a_oFile);
		}
		void FileDownloadFailedSafe(Course a_oCourse, FolderItem a_oFolder, FileItem a_oFile)
		{
			try
			{
				toolStripProgressBar.ProgressBar.Value++;
			}
			catch(Exception e)
			{
				CLogger.ReportException(e);
			}
		}
		void FileDownloadEndedSuccessfully(Course a_oCourse, FolderItem a_oFolder, FileItem a_oFile)
		{
			// Thread Safe Updating
			this.Invoke(new FileDownloadDelegate(FileDownloadEndedSuccessfullySafe), a_oCourse, a_oFolder, a_oFile);
		}
		void FileDownloadEndedSuccessfullySafe(Course a_oCourse, FolderItem a_oFolder, FileItem a_oFile)
		{
			try
			{
				toolStripProgressBar.ProgressBar.Value++;
			}
			catch (Exception e)
			{
				CLogger.ReportException(e);
			}
		}
		void FileDownloadStarted(Course a_oCourse, FolderItem a_oFolder, FileItem a_oFile)
		{
			// Thread Safe Updating
			this.Invoke(new FileDownloadDelegate(FileDownloadStartedSafe), a_oCourse, a_oFolder, a_oFile);
		}
		private void FileDownloadStartedSafe(Course a_oCourse, FolderItem a_oFolder, FileItem a_oFile)
		{
			toolStripStatusLabelCourseName.Text = a_oCourse.Name + "    - ";

			toolStripStatusLabelCurrentStatus.Text = "מוריד את: " + a_oFile.Name;
		}

		private void ExecuterCoursesLoaded()
		{
			// Thread Safe Updating
			this.Invoke(new SimpleDelegate(CoursesLoaded));
		}

		private void CourseInformationUpdated(String a_sCourseName)
		{
			this.Invoke(new CourseUpdatedDelegate(CourseInformationUpdatedSafe), a_sCourseName);
		}
		private void CourseInformationUpdatedSafe(String a_sCourseName)
		{
			// Stop the loading animation
			m_oAnimator.RemoveItem(a_sCourseName);

			RefreshCourseDetails();
		}
		private void CourseInformationRequest(string a_sCourseName)
		{
			this.Invoke(new CourseUpdatedDelegate(CourseInformationRequestSafe), a_sCourseName);
		}
		private void CourseInformationRequestSafe(String a_sCourseName)
		{
			m_oAnimator.AddItem(listViewCourses.Items.Find(a_sCourseName, false)[0], a_sCourseName);
		}

		#endregion

		private void SetCourseListItemLooks(ListViewItem a_oItem, Course a_oCourse)
		{
			if (!(a_oCourse.DataRetrieved == ERetrievedState.NotRetrieved))
			{
				a_oItem.Font = new Font(a_oItem.Font, FontStyle.Bold);
			}
			else
			{
				a_oItem.Font = new Font(a_oItem.Font, FontStyle.Regular);
			}

			a_oItem.ImageIndex = (int)m_oCore.DataCenter.Courses[a_oItem.Text].DataRetrieved;

			if (!a_oCourse.CourseExists)
			{
				a_oItem.ForeColor = Color.Gray;
				a_oItem.ImageIndex = 3; // Put a gray icon
			}
			else
			{
				a_oItem.ForeColor = Color.Black;
			}
		}

		#region GUI - Datacenter Update methods
		private void UpdateTreeNode(TreeNode a_oNode, FolderItem a_oFolder)
		{
			// Bad encapsulation alert!
			// The tree nodes are created in 2 different places - Here and in the RefreshCourseDetails method.

			TreeNode l_oNode;
			
			a_oNode.Checked = a_oFolder.Download;

			foreach (FolderItem l_oFolder in a_oFolder.Folders.Values)
			{
				l_oNode = new TreeNode(l_oFolder.Name);
				l_oNode.Name = l_oFolder.Name;

				a_oNode.Nodes.Add(l_oNode);
				UpdateTreeNode(l_oNode, l_oFolder);
			}
		}

		/// <summary>
		/// Refreshes the GUI according to the new selected course.
		/// </summary>
		private void RefreshCourseDetails()
		{
			TreeNode l_oNode;
			Course l_oIteratedCourse;

			// Not sure why this happens, but the function shouldn't work when no item is selected
			if (listViewCourses.SelectedItems.Count == 0)
			{
				m_oCore.Core.logger.WriteLn("RefreshCourseDetails Ignoring Request (no item selected)");
				return;
			}

			treeViewFolders.Nodes.Clear();
			checkedListBoxFiles.Items.Clear();

			m_oCurrentCourse = m_oCore.DataCenter.Courses[listViewCourses.SelectedItems[0].Text];

			if (listViewCourses.SelectedItems.Count > 0)
			{
				m_bTreeViewPopulating = true;
				foreach (FolderItem l_oFolder in m_oCurrentCourse.Data.Folders.Values)
				{
					// Bad encapsulation alert!
					// The tree nodes are created in 2 different places - Here and in the UpdateTreeNode method.
					l_oNode = treeViewFolders.Nodes.Add(l_oFolder.Name);
					l_oNode.Name = l_oFolder.Name;
					UpdateTreeNode(l_oNode, l_oFolder);
				}
				m_bTreeViewPopulating = false;

				foreach (ListViewItem l_oItem in listViewCourses.Items)
				{
					l_oIteratedCourse = m_oCore.DataCenter.Courses[l_oItem.Text];
					SetCourseListItemLooks(l_oItem, l_oIteratedCourse);
				}
			}
		}

		private void RefreshFilesDetails()
		{
			int l_iFileIndex;

			if (treeViewFolders.SelectedNode != null)
			{
				m_oCurrentFolder = m_oCurrentCourse.GetFolderAt(treeViewFolders.SelectedNode.FullPath);

				checkedListBoxFiles.Items.Clear();

				foreach (FileItem l_oFile in m_oCurrentFolder.Files.Values)
				{
					l_iFileIndex = checkedListBoxFiles.Items.Add(l_oFile.ToString());
					checkedListBoxFiles.SetItemChecked(l_iFileIndex, l_oFile.Download);
				}
			}
		}

		private void RefreshFoldersCheckedState()
		{
			foreach (FolderItem l_oFolder in m_oCurrentCourse.Data.Folders.Values)
			{
//				treeViewFolders.Nodes.IndexOfKey(l_oFolder.Name);
				RefreshFoldersCheckedState(l_oFolder, treeViewFolders.Nodes[l_oFolder.Name]);
			}
		}

		private void RefreshFoldersCheckedState(FolderItem a_oFolder, TreeNode a_oNode)
		{
			TreeNode[] l_oNode;

			a_oNode.Checked = a_oFolder.Download;

			foreach (FolderItem l_oFolder in a_oFolder.Folders.Values)
			{
				l_oNode = a_oNode.Nodes.Find(l_oFolder.Name, false);
				RefreshFoldersCheckedState(l_oFolder, l_oNode[0]);
			}
		}
		#endregion


		/// <summary>
		/// Loads courses data from a file
		/// </summary>
		public void CoursesLoadFromFile()
		{
			// Load the previously saved courses from file
			if (File.Exists(m_sCoursesFilePath))
			{
				FileStream l_oStream = File.Open(m_sCoursesFilePath, FileMode.Open);
				BinaryFormatter l_oBinFormatter = new BinaryFormatter();

				m_oCore.DataCenter = (CDataCenter)l_oBinFormatter.Deserialize(l_oStream);

				l_oStream.Close();

				CoursesLoaded();

				CoursesLoading();
			}

			m_oCore.DataCenter.SaveFilename = m_sCoursesFilePath;
			m_oCore.DataCenter.AllowSaving = Properties.Settings.Default.SaveUserCourses;
		}

		public void CoursesLoading()
		{
			m_bCoursesLoaded = false;
			timerHoldOn.Start();
		}

		private void CoursesLoaded()
		{
			ListViewItem l_oItem;

			foreach (Course l_oCourse in m_oCore.DataCenter.Courses.Values)
			{
				l_oItem = listViewCourses.FindItemWithText(l_oCourse.ToString());
				if (l_oItem == null)
				{
					l_oItem = listViewCourses.Items.Add(l_oCourse.ToString());
					l_oItem.Name = l_oCourse.ToString();
					l_oItem.Checked = l_oCourse.Download;
					l_oItem.ImageIndex = (int)l_oCourse.DataRetrieved;
				}

				SetCourseListItemLooks(l_oItem, l_oCourse);
			}

			if (listViewCourses.SelectedIndices.Count == 0)
			{
				listViewCourses.Items[0].Selected = true;
			}

			m_bCoursesLoaded = true;
			timerHoldOn.Stop();
			labelHoldOn.Visible = false;
		}

		private void FormMain_Load(object sender, System.EventArgs e)
		{
			SetGUIState(EState.Disconnected);

			if (Properties.Settings.Default.Username == "")
			{
				if (ShowSettings() != DialogResult.OK)
				{
					CLogger.LogMessage("Settings Error. Exiting...");
					Application.Exit();
					return;
				}
			}

			StartConnection();

			if (Properties.Settings.Default.CheckUpdatesAutomatically)
			{
				CheckUpdates();
			}
		}

		private void SetGUIState(EState a_eState)
		{
			switch (a_eState)
			{
				case EState.Disconnected:
					UpdateCurrentStatus("הקבצים יישמרו אל " + Properties.Settings.Default.SavePath);
					UpdateGeneralStatus("מנותק");

					toolStripStatusLabelGeneralStatus.ForeColor = Color.Red;

					//buttonAbort.Enabled = false;
					//buttonStart.Enabled = true;

					buttonStartDownloading.Enabled = false;

					break;

				case EState.Connected:
					UpdateGeneralStatus("מחובר");
					toolStripStatusLabelGeneralStatus.ForeColor = Color.Green;

					toolStripProgressBar.Enabled = false;// Value = 0;
					toolStripStatusLabelCourseName.Text = "";


					//buttonAbort.Enabled = true;
					//buttonStart.Enabled = false;

					buttonStartDownloading.Enabled = true;

					break;

				case EState.Downloading:
					UpdateCurrentStatus("מכין קבצים...");
					toolStripProgressBar.Value = 0;


					//buttonAbort.Enabled = true;
					//buttonStart.Enabled = false;

					buttonStartDownloading.Enabled = false;
					
					break;
			}
		}

		private void StartConnection()
		{
			CLogger.LogFunctionEntry();
			Initialize();

			labelTop.Text = "ברוכים הבאים, " + Properties.Settings.Default.Username;

			m_oCore.CONFIG_USERNAME = Properties.Settings.Default.Username;
			m_oCore.CONFIG_PASSWORD = Utilities.CAESEncyption.Decrypt(Properties.Settings.Default.Password);

			m_sCoursesFilePath = m_sConfigurationDirectory + m_oCore.CONFIG_USERNAME + COURSES_FILE_PATH_END;

			// For Testing
			if (DEBUG_COURSE)
			{
				TestingUtilites.SimulateCourseLoading(m_oCore, "דוגמא", "Dump.dump");
				TestingUtilites.SimulateCourseLoading(m_oCore, "1דוגמא", "Dump.dump");
				TestingUtilites.SimulateCourseLoading(m_oCore, "2דוגמא", "Dump.dump");
			}
			else
			{
				m_oCore.Connect(true);

				CoursesLoadFromFile();

				CoursesLoading();

				m_oCore.GetAvailibleCourses(true);
			}
		}

		private void AbortConnection()
		{
			m_oCore.Disconnect();
		}

		private bool CheckUpdates()
		{
			AutoUpdater.CAutoUpdater l_oUpdater = new AutoUpdater.CAutoUpdater("http://spofer.com/Highlearner/Latest.xml", true);

			if (l_oUpdater.CompareVersions(l_oUpdater.LatestVersion, Application.ProductVersion) == 1)
			{
				if (MessageBox.Show(
					"?האם ברצונך לעדכן" + " ," + "Highlearner" + " ישנה גרסה מעודכנת יותר של",
					"Version update",
					MessageBoxButtons.YesNo,
					MessageBoxIcon.Question) == DialogResult.Yes)
				{
					new FormUpdate(l_oUpdater).Show();
				}
				return true;
			}

			return false;
		}

		private DialogResult ShowSettings()
		{
			DialogResult l_oResult;
			FormSettings l_oSettings = new FormSettings();
			l_oSettings.ShowInTaskbar = false;
			l_oResult = l_oSettings.ShowDialog();

			if (m_oCore != null)
			{
				m_oCore.DataCenter.AllowSaving = Properties.Settings.Default.SaveUserCourses;
			}

			return l_oResult;
		}

		private void listViewCourses_MouseDoubleClick(object sender, MouseEventArgs e)
		{
			ListViewItem l_oItem;

			if (e.Button == MouseButtons.Left)
			{
				l_oItem = listViewCourses.GetItemAt(e.X, e.Y);
				if (m_bCoursesLoaded)
				{
					if (l_oItem.Index > -1)
					{
						m_oCore.GetCourseInformation(m_oCore.DataCenter.Courses[l_oItem.Text].Name, false, true);
					}
				}
				else
				{
					l_oItem.Checked = false;
				}
			}
		}

		private void listViewCourses_SelectedIndexChanged(object sender, EventArgs e)
		{
			RefreshCourseDetails();
		}

		private void treeViewFolders_AfterSelect(object sender, TreeViewEventArgs e)
		{
			RefreshFilesDetails();
		}

		private void buttonStartDownloading_Click(object sender, EventArgs e)
		{
			m_oCore.SavePath = Properties.Settings.Default.SavePath;

			SetGUIState(EState.Downloading);

			foreach (ListViewItem l_oItem in listViewCourses.Items)
			{
				m_oCore.DataCenter.Courses[l_oItem.Text].Download = l_oItem.Checked;
			}

			m_oCore.DownloadAll(true);
		}

		private void treeViewFolders_AfterCheck(object sender, TreeViewEventArgs e)
		{
			// Prevent running when the tree is populated
			if (!m_bTreeViewPopulating)
			{
				// Get the relevant folder
				FolderItem l_oFolder = m_oCore.DataCenter.Courses[listViewCourses.SelectedItems[0].Text].Data.GetFolder(e.Node.FullPath);

				if ((e.Action == TreeViewAction.ByKeyboard) || (e.Action == TreeViewAction.ByMouse))
				{
					// And set!
					l_oFolder.Download = e.Node.Checked;

					RefreshFoldersCheckedState(l_oFolder, e.Node);
					RefreshFilesDetails();
				}
			}
		}

		private void SetCheckedState(Control a_oControl, Boolean a_bState)
		{
			if (a_oControl == listViewCourses)
			{
				foreach (ListViewItem l_oItem in listViewCourses.Items)
				{
					l_oItem.Checked = a_bState;
				}
			}
			if (a_oControl == checkedListBoxFiles)
			{
				if (m_oCurrentFolder != null)
				{
					m_oCurrentFolder.Download = a_bState;
					RefreshFilesDetails();
				}
			}
			if (a_oControl is TreeView)
			{
				foreach (FolderItem l_oFolder in m_oCurrentCourse.Data.Folders.Values)
				{
					l_oFolder.Download = a_bState;
				}
				foreach (FileItem l_oFile in m_oCurrentCourse.Data.Files.Values)
				{
					l_oFile.Download = a_bState;
				}

				RefreshFoldersCheckedState();
			}
		}

		private void toolStripMenuItemMarkAll_Click(object sender, EventArgs e)
		{
			SetCheckedState(contextMenuStripRight.SourceControl, true);
		}
		private void toolStripMenuItemUnMarkAll_Click(object sender, EventArgs e)
		{
			SetCheckedState(contextMenuStripRight.SourceControl, false);
		}
		private void toolStripMenuItemDownloadCourseInformation_MouseDown(object sender, MouseEventArgs e)
		{
			if (listViewCourses.SelectedItems.Count > 0)
			{
				m_oCore.GetCourseInformation(listViewCourses.SelectedItems[0].Text, true, true);
			}
		}

		private void checkedListBoxFiles_ItemCheck(object sender, ItemCheckEventArgs e)
		{
			if (m_oCurrentFolder != null)
			{
				m_oCurrentFolder.Files[checkedListBoxFiles.Items[e.Index].ToString()].Download = (e.NewValue == CheckState.Checked);
			}
		}

		private void contextMenuStripFolders_Click(object sender, EventArgs e)
		{

		}

		private void אודותToolStripMenuItem_Click(object sender, EventArgs e)
		{
			(new frm_About()).Show();
		}
		private void יציאהToolStripMenuItem_Click(object sender, EventArgs e)
		{
			Application.Exit();
		}

		private void listViewCourses_MouseDown(object sender, MouseEventArgs e)
		{
			if (e.Button == MouseButtons.Right)
			{
				if (listViewCourses.GetItemAt(e.X, e.Y) != null)
				{
					contextMenuStripCourses.Show(listViewCourses, e.X, e.Y);
				}
			}
		}

		private void הגדרותToolStripMenuItem_Click(object sender, EventArgs e)
		{
			ShowSettings();

			if (m_oCore.CONFIG_USERNAME != Properties.Settings.Default.Username)
			{
				AbortConnection();

				// This should reload the user and reinitizlize the hl
				StartConnection();
			}
		}

		private void בדוקעדכוניםToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if (!CheckUpdates())
			{
				MessageBox.Show("בידך הגרסה העדכנית ביותר", "עדכון גרסה", MessageBoxButtons.OK, MessageBoxIcon.Information);

			}

		}

		private void buttonOpenDownloadsDirectory_Click(object sender, EventArgs e)
		{
			// Check what happens if there is no security
			if (Directory.Exists(Properties.Settings.Default.SavePath))
			{
				System.Diagnostics.Process.Start(Properties.Settings.Default.SavePath);
			}
		}

		private void panelFilesManagment_Resize(object sender, EventArgs e)
		{
			int l_iSize = panelControl.Width;
			// | 3 | Button | 1 | 1 | Buttion | 3 |
			int l_iButtonSize = ((l_iSize - 10) / 2);
			
			buttonOpenDownloadsDirectory.Left = 3;
			buttonOpenDownloadsDirectory.Width = l_iButtonSize;
			buttonStartDownloading.Left = buttonOpenDownloadsDirectory.Left + l_iButtonSize + 2;
			buttonStartDownloading.Width = l_iButtonSize;
		}

		private void timerHoldOn_Tick(object sender, EventArgs e)
		{
			labelHoldOn.Visible = !labelHoldOn.Visible;

		}

		private void נקהקורסיםישניםToolStripMenuItem_Click(object sender, EventArgs e)
		{
			/*
			 * Removed for this version. Maybe next one!
			 * 
			m_oCore.DataCenter.CleanupOldCourses();

			listViewCourses.Clear();

			CoursesLoaded();
			*/
		}
	}
}
